package A1_二叉树;

import java.util.ArrayList;
import java.util.List;

public class LC_501二叉搜索树中的众数_动态数组 {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val=val;
        }
        TreeNode(int val,TreeNode left,TreeNode right){
            this.val=val;
            this.left=left;
            this.right=right;
        }
    }
    TreeNode pre=null;
    int count=0;
    int maxcount=0;
    ArrayList result=new ArrayList();
//    List<Integer> list=new ArrayList<>();
    public int[] findMode(TreeNode root) {
        traversal(root);
    //        return result;
        int[] res=new int[result.size()];
        for(int i=0;i<result.size();i++)
            res[i]= (int) result.get(i);//获取的是下标
        return res;
    }
    public void traversal(TreeNode cur){
        if(cur==null)
            return;
        traversal(cur.left);
        if(pre==null)
            count=1;
        else if(pre.val==cur.val)
            count++;
        else
            count=1;
        pre=cur;
        if(count==maxcount)
//            result.add(cur.val);
            result.add(cur.val);
        if(count>maxcount){
            maxcount=count;
//            result.clear();
//            result.add(cur.val);
            result.clear();
            result.add(cur.val);
        }
        traversal(cur.right);
    }
}
